package cn.newx.unit
{
	import cn.newx.unit.Events.PlayerLoadEvent;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.net.LocalConnection;
	import flash.net.URLRequest;
	
	public class PlayerDoc extends EventDispatcher
	{
		public function PlayerDoc(head:String,body:String)
		{
			_head = ASSET+'head/'+head;
			_body = ASSET+'avatar/'+body;
			_p=0;
			player = new Sprite();
		}
		
		public function startLoad():void
		{
			myLoader=new Loader();
			myLoader.contentLoaderInfo.addEventListener(Event.COMPLETE,loadNext);
			myLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR,ioErrorHandle);
			myLoader.load(new URLRequest(_body));
		}
		
		public function get Data():BitmapData
		{
			return this.doc;
		}
		
		private function loadNext(e:Event):void
		{
			switch(_p)
			{
				case 0:
					var _temp0:BitmapData=new BitmapData(myLoader.width,myLoader.height,true,0x00FFFFFF);
					_temp0.draw(myLoader);
					var _img0:Bitmap = new Bitmap(_temp0);
					player.addChild(_img0);
					myLoader.load(new URLRequest(_head));
					break;
				case 1:
					var _temp1:BitmapData=new BitmapData(myLoader.width,myLoader.height,true,0x00FFFFFF);
					_temp1.draw(myLoader);
					var _img1:Bitmap = new Bitmap(_temp1);
					player.addChild(_img1);
					buildPlayerDoc();
					break;
				default:
					dispatchEvent(_playerLoadE);
					break;
			}
			_p++;
		}
		
		private function buildPlayerDoc():void
		{
			doc = new BitmapData(player.width,player.height,true,0x00FFFFFF);
			doc.draw(player);
			player=null;
			GC();
			dispatchEvent(_playerLoadE);
		}
		
		private function ioErrorHandle(e:IOErrorEvent):void
		{
		}
		
		public function clear():void
		{
			delete this;
			GC();
		}
		
		// 强制内存回收
		private function GC():void
		{
			try 
            { 
                var lc1:LocalConnection = new LocalConnection(); 
                var lc2:LocalConnection = new LocalConnection(); 
                lc1.connect('name'); 
                lc2.connect('name2'); 
            } 
            catch (e:Error) 
            { 
            } 
		}
		
		public var _head:String;
		public var _body:String;
		public var _p:uint; // 加载指针
		public var myLoader:Loader;
		public var player:Sprite;
		public var doc:BitmapData;
		public static var ASSET:String = 'asset/unit/';
		private var _playerLoadE:PlayerLoadEvent = new PlayerLoadEvent();
	}
}